// pages/component/homes/purchase/payment/payment.js
var that;
var dataManager = require('../../../../../utils/dataManager.js');
var GlobalData = require('../../../../../utils/GlobalData.js');
var Util = require('../../../../../utils/util.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pay: [],
    money: 0,
    orderno: "",
    selected: 0,
    id: 0,
    sysno: "",
    time: "",
    //支付页面数据
    rechargetype:"",
    nametype:"",
    playername:"",
    idtype:"",
    playerid:"",
    iszhifushow:false,
    isTemplateshow:false,
    // 免密支付
    isShow: false,
    inputPassWord: "",
    totalCount: 0,
    isPay: false,
    hidden: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    dataManager.removeBtnObserver("payment")
    this.setData({
      hidden: true
    })
    if (GlobalData.PayType && GlobalData.PayType[GlobalData.PayReason]) {
      this.onComplete();
    } else {
      dataManager.rigisterObserver("paytype", this.onComplete, this);
      dataManager.getPayType();
    }

  },
  onComplete: function () {
    var payArr = [];
    if (GlobalData.PayType && GlobalData.PayType[GlobalData.PayReason])
      payArr = GlobalData.PayType[GlobalData.PayReason];
    // console.log(payArr);
    for (let i = 0; i < payArr.length; i++) {
      if (payArr[i]["type"] == 4) {
        let temp = payArr[i];
        payArr.splice(i, 1)
        payArr.unshift(temp);
        break;
      }
    }
    if (this.data.selected) {
      payArr[this.data.selected]["selected"] = true;
    } else {
      for (let i = 0; i < payArr.length; i++) {
        if (i == 0)
          payArr[i]["selected"] = true;
        else
          payArr[i]["selected"] = false;
      }
    }
    // console.log(GlobalData.order["nametype"])
    if (!GlobalData.order["nametype"]){
      this.setData({
        iszhifushow: false
      })
    }else{
      this.setData({
        iszhifushow: true
      })
    }
    // (GlobalData.order && GlobalData.order["sysno"]) ? GlobalData.order["sysno"] : 0
    if (GlobalData.order["nametype"]){
      this.setData({
        totalCount: (GlobalData.order && GlobalData.order["totalcount"]) ? GlobalData.order["totalcount"] : 0,
        pay: payArr,
        money: GlobalData.order && GlobalData.order["money"],
        orderno: GlobalData.order && GlobalData.order["orderno"],
        id: (GlobalData.order && GlobalData.order["id"]) ? GlobalData.order["id"] : 0,
        sysno: (GlobalData.order && GlobalData.order["sysno"]) ? GlobalData.order["sysno"] : 0,
        time: GlobalData.order && GlobalData.order["time"],
        rechargetype: GlobalData.order && GlobalData.order["rechargetype"],
        nametype: GlobalData.order && GlobalData.order["nametype"],
        playername: GlobalData.order && GlobalData.order["playername"],
        idtype: GlobalData.order && GlobalData.order["idtype"],
        playerid: GlobalData.order && GlobalData.order["playerid"],
        moneystr: (GlobalData.homeData.accountbalance < this.data.money) ? "余额不足 (当前余额：" + GlobalData.homeData.accountbalance + ")" : "用余额支付更便捷。",
      })
    }else{
      this.setData({
        totalCount: (GlobalData.order && GlobalData.order["totalcount"]) ? GlobalData.order["totalcount"] : 0,
        pay: payArr,
        money: GlobalData.order && GlobalData.order["money"],
        orderno: GlobalData.order && GlobalData.order["orderno"],
        id: (GlobalData.order && GlobalData.order["id"]) ? GlobalData.order["id"] : 0,
        sysno: (GlobalData.order && GlobalData.order["sysno"]) ? GlobalData.order["sysno"] : 0,
        time: GlobalData.order && GlobalData.order["time"],
        rechargetype: GlobalData.order && GlobalData.order["rechargetype"],
        // nametype: GlobalData.order && GlobalData.order["nametype"],
        // playername: GlobalData.order && GlobalData.order["playername"],
        // idtype: GlobalData.order && GlobalData.order["idtype"],
        // playerid: GlobalData.order && GlobalData.order["playerid"],
        moneystr: (GlobalData.homeData.accountbalance < this.data.money) ? "余额不足 (当前余额：" + GlobalData.homeData.accountbalance + ")" : "用余额支付更便捷。",
      })
    }
    
    // console.log("aaaaaa", this.data.pay);
  },
  //点击弹框返回按钮
  onTurnoff: function () {
    this.setData({
      isTemplateshow: false
    })
  },
  //点击弹框确认充值按钮
  onTurnon: function () {
    this.setData({
      isTemplateshow: false
    })
    this.onPay();
  },
  onPaydown:function(){
    if (GlobalData.order["owntype"]){
      this.setData({
        isTemplateshow: true
      })
    }else{
      this.onPay();
    }
    
  },

  /**选择支付方式 */
  radioChange: function (e) {
    var index = e.detail.value;
    // console.log(index);
    var payArr = GlobalData.clone(this.data.pay)
    for (let i = 0; i < payArr.length; i++) {
      if (i != index) {
        payArr[i]["selected"] = false;
      }
      else
        payArr[i]["selected"] = true;
    }
    this.setData({
      pay: payArr,
      selected: index,
    })


  },
  /**点击确认支付 */
  /**确认支付 */
  onPay: function () {
    /**余额充值输入支付密码 */
    if (this.data.pay[this.data.selected]["type"] == 4) {
      if (GlobalData.homeData && !GlobalData.homeData.ispaypass) {
        this.setData({
          hidden: false
        })
        app.onTip("请先设置支付密码。", '../../../homes/setpaypsword/setpaypsword?url=payment', false);
      }
      else {
        //输入密码支付
        // console.log("免密", GlobalData.homeData.isopenpaypass);
        if (GlobalData.homeData["isopenpaypass"] == 0) {

          if (GlobalData.homeData.accountbalance < this.data.money) {

            wx.showModal({
              title: '提示',
              content: "余额不足，请充值。",
              showCancel: true,
              success: function (res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '/pages/component/homes/purchase/moneyrecharge/moneyrecharge'
                  })
                }
              }
            })
            return;
          }

          this.setData({
            isopenpaypass: GlobalData.homeData.isopenpaypass,
            isShow: true
          })
        }
        else
          //免密支付
          this.finalPay();
      }
    }
    else
      this.finalPay();
  },
  /**最后的支付 */
  finalPay: function () {
    var that = this
    // if (GlobalData.ispay) {
    //   return
    // }
    // GlobalData.ispay = true;
    // console.log(this.data.pay, "最后支付", GlobalData.PayReason);
    this.setData({
      hidden: false
    })
    // ok-oq5H_xjwEdYf8vkvo-PIsLjtc
    /**充值 */
    if (GlobalData.PayReason == 1) {
      // wx.navigateBack({
      //   delta: 3
      // })
      dataManager.OnRequestPost({ method: "pay_recharge_jsapi", "token": GlobalData.token, "paytype": that.data.pay[that.data.selected]["type"], "id": that.data.id, "openid": app.getOpenID(), source: 1 }, this.onMoneyRecharge, false, this.onError);
    }
    /**购卡 */
    else if (GlobalData.PayReason == 2) {
      //openid是否为空
      // if ((GlobalData.openid == null || GlobalData.openid == "")) {}
      dataManager.OnRequestPost({ method: "pay_product_jsapi", "token": GlobalData.token, "paytype": that.data.pay[that.data.selected]["type"], "sysno": that.data.sysno, "openid": app.getOpenID(), source: 1 }, this.onBuyCard, false, this.onError);
    }
    /**直充 */
    else if (GlobalData.PayReason == 3) {
      dataManager.OnRequestPost({ method: "pay_product", "token": GlobalData.token, "paytype": that.data.pay[that.data.selected]["type"], "sysno": that.data.sysno }, this.onRecharge, false, this.onError);
      /**俱乐部直充 */
    } else if (GlobalData.PayReason == 4) {
      dataManager.OnRequestPost({ method: "pay_product", "token": GlobalData.token, "paytype": that.data.pay[that.data.selected]["type"], "sysno": that.data.sysno }, this.onClubPay, false, this.onError);
    }
  },
  onError: function () {
    this.setData({
      hidden: true
    })
  },
  /**购卡处理函数 */
  onBuyCard: function (data) {
    var that = this;
    //清空购卡记录
    GlobalData.BuyCardRecord.splice(0, GlobalData.BuyCardRecord.length);
    GlobalData.BuyCardRecordother["index"] = 1
    GlobalData.carddetail = data.logid;
    // console.log(GlobalData.carddetail)
    if (that.data.pay[that.data.selected]["type"] == 4) {
      //购买成功清空购物车
      // console.log("GlobalData.BuyCardRecord.length", GlobalData.BuyCardRecord, GlobalData.shopcar_1);
      GlobalData.shopcar_1.splice(0, GlobalData.shopcar_1.length);

      if (GlobalData.isTakeCard == 0) {
        dataManager.OnRequestPost({ method: "getagentgame", "token": GlobalData.token }, that.onProcessDepotKind);
      }
      else {
        // GlobalData.carddetail = data.logid;
        /**清空取卡列表 */
        GlobalData.GetCardRecord.splice(0, GlobalData.GetCardRecord.length);
        GlobalData.GetCardRecordother["index"] = 1;

        /**判断买多张还是单张  getcarddetail  getcardrecord*/
        if (that.data.totalCount == 1) {
          dataManager.rigisterObserver("getcarddetail", that.onGetcarddetail, that);
          dataManager.getGetCardDetail();
        } else {
          dataManager.OnRequestPost({ method: "getagentcdkeyloglist", "token": GlobalData.token, "pageindex": GlobalData.GetCardRecordother["index"], "pagesize": GlobalData.GetCardRecordother["size"] }, that.onProcessGetCardRecord);

        }
      }
    }
    else if (that.data.pay[that.data.selected]["type"] == 1) {

      // 微信支付
      // that.data.renderer.setStyle(that.data.bg.nativeElement, "display", "block");
      // GlobalData.extern.pay(pkg.data);
      // console.log(GlobalData.shopcar_1, "购卡记录");
      that.wxPay(data)
    }
  },
  /**跳到取卡记录 */
  onProcessGetCardRecord: function (data) {
    GlobalData.ispay = false;
    for (let i = 0; i < data.length; i++)
      GlobalData.GetCardRecord[i] = data[i];
    this.setData({
      hidden: false
    })
    wx.redirectTo({
      url: '../../../carddepots/getcardrecord/getcardrecord',
    })


  },
  /**跳到取卡详情 */
  onGetcarddetail: function (data) {

    this.setData({
      hidden: false
    })
    wx.redirectTo({
      url: '../../../carddepots/getcarddetail/getcarddetail',
    })


  },

  /**余额支付购卡 */
  onProcessDepotKind: function (data) {
    GlobalData.DepotKind = [];
    for (let i = 0; i < data.length; i++)
      GlobalData.DepotKind[i] = data[i];
    // console.log("卡库分类", GlobalData.DepotKind);
    dataManager.OnRequestPost({ method: "getcdkeycount", "token": GlobalData.token }, this.onProcessDepotCard);
  },
  onProcessDepotCard: function (data) {
    GlobalData.DepotCard = [];
    for (let i = 0; i < data.length; i++) {
      GlobalData.DepotCard[i] = GlobalData.clone(data[i]);
      for (let j = 0; j < GlobalData.DepotKind.length; j++) {
        if (GlobalData.DepotKind[j]["gameid"] == GlobalData.DepotCard[i]["game_id"])
          GlobalData.DepotCard[i]["gamename"] = GlobalData.DepotKind[j]["title"];
      }
    }

    GlobalData.ispay = false;
    GlobalData.isSave = true;
    app.onTip("下单成功，稍后可在你的卡库中查看。", '../../../carddepots/carddepot/carddepot', true);


  },

  /**调起微信支付 */
  wxPay: function (wxData) {
    var that = this;
    var data = JSON.parse(wxData);
    // console.log(data);
    wx.requestPayment(
      {
        'timeStamp': data.timeStamp,
        'nonceStr': data.nonceStr,
        'package': data.package,
        'signType': 'MD5',
        'paySign': data.paySign,
        'success': function (res) {
          GlobalData.ispay = false;
          if (GlobalData.PayReason == 1) {
            // if (dataManager.isClick("home")) {
            //   return
            // } else {
            //   dataManager.btnObserver("home")
            GlobalData.ispay = false;

            app.onTip("充值成功。", '../../../homes/home/home', true);
            // }
          } else {
            //购买成功清空购物车
            // console.log("GlobalData.BuyCardRecord.length", GlobalData.BuyCardRecord, GlobalData.shopcar_1);
            GlobalData.shopcar_1.splice(0, GlobalData.shopcar_1.length);
            // console.log(res)
            // console.log("GlobalData.BuyCardRecord.length", GlobalData.BuyCardRecord, GlobalData.shopcar_1);
            GlobalData.shopcar_1.splice(0, GlobalData.shopcar_1.length);
            GlobalData.ispay = false;
            if (GlobalData.isTakeCard == 0) {
              dataManager.OnRequestPost({ method: "getagentgame", "token": GlobalData.token }, that.onProcessDepotKind);
            }
            else {
              // GlobalData.carddetail = data.logid;
              /**清空取卡列表 */
              GlobalData.GetCardRecord.splice(0, GlobalData.GetCardRecord.length);
              GlobalData.GetCardRecordother["index"] = 1;
              /**判断买多张还是单张  getcarddetail  getcardrecord*/
              // if (that.data.totalCount == 1) {
              //   dataManager.rigisterObserver("getcarddetail", that.onGetcarddetail, that);
              //   dataManager.getGetCardDetail();
              // } else {
                dataManager.OnRequestPost({ method: "getagentcdkeyloglist", "token": GlobalData.token, "pageindex": GlobalData.GetCardRecordother["index"], "pagesize": GlobalData.GetCardRecordother["size"] }, that.onProcessGetCardRecord);

              // }
            }
            // app.onTip("购买成功", '../../../homes/home/home', true);
          }
        },
        'fail': function (res) {
          // console.log(res)
          GlobalData.ispay = false;
        },
        'complete': function (res) {
          // console.log(res)
          that.setData({
            hidden: true
          })
        }
      })
  },
  /**充值支付的处理函数 */
  onMoneyRecharge: function (data) {
    var that = this;
    GlobalData.ispay = false;
    /**弹框请确认微信支付是否完成 */
    //       this.renderer.setStyle(this.bg.nativeElement, "display", "block");

    that.wxPay(data)
    // console.log("微信支付是否完成？已完成", data);
  },
  /**直充的处理函数 */
  onRecharge: function (data) {
    that = this;
    GlobalData.ispay = false;
    // console.log("直充成功之后，", pkg);
    //清空购物车
    GlobalData.shopcar_2.splice(0, GlobalData.shopcar_2.length);
    //清空直充记录
    GlobalData.RechargeRecord.splice(0, GlobalData.RechargeRecord.length);
    GlobalData.RechargeRecordother["index"] = 1;
    if (that.data.pay[that.data.selected]["type"] == 4) {
      GlobalData.ispay = false;
      // if (dataManager.isClick("home")) {
      //   return
      // } else {
      //   dataManager.btnObserver("home")
      app.onTip("充值成功。", '../../../homes/home/home', true);
      // }
      // app.onTip("直充成功。", '../../../homes/home/home', true);
    }
  },
  /**俱乐部 */
  onClubPay: function (data) {
    that = this;
    GlobalData.ispay = false;
    // console.log("直充成功之后，", pkg);
    //清空购物车
    GlobalData.shopcar_2.splice(0, GlobalData.shopcar_2.length);
    //清空直充记录
    GlobalData.ClubRechargeRecord.splice(0, GlobalData.ClubRechargeRecord.length);
    GlobalData.ClubRechargeRecordother["index"] = 1;
    if (that.data.pay[that.data.selected]["type"] == 4) {
      // if (dataManager.isClick("home")) {
      //   return
      // } else {
      //   dataManager.btnObserver("home")
      GlobalData.ispay = false;
      app.onTip("俱乐部充值成功。", '../../../homes/home/home', true);
      // }

    }
  },
  /**输入登录密码 */
  onInputPassWord: function (e) {
    this.setData({
      inputPassWord: e.detail.value
    })
    // console.log(this.data.inputPassWord)
  },

  onClose: function () {
    this.setData({
      isShow: false
    })
  },
  /**忘记支付密码 */
  goForGetPassWord: function () {

    // if (dataManager.isClick("setpaypsword")) {
    //   return
    // } else {
    //   dataManager.btnObserver("setpaypsword")
    this.setData({
      hidden: false
    })
    dataManager.UseNavigateTo('../../../homes/setpaypsword/setpaypsword', false);
    // }


  },
  /**返回首页 */
  bindViewTap: function () {
    // if (dataManager.isClick("home")) {
    //   return
    // } else {
    //   dataManager.btnObserver("home")
    this.setData({
      hidden: false
    })
    dataManager.UseNavigateTo('../../../homes/home/home', true);
    // }

  },


  onSetWithoutCode: function () {
    if (this.data.inputPassWord == "" || this.data.inputPassWord.length != 6) {
      app.show("请输入6位数支付密码");
      return;
    }
    dataManager.OnRequestPost({ method: "validatepaypass", token: GlobalData.token, "paypass": this.data.inputPassWord }, this.onprocessWithoutCode);
  },
  onprocessWithoutCode: function (data) {
    this.finalPay();
    this.setData({
      isShow: false
    })
  },




  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})